package object

import (
	"github.com/julienschmidt/httprouter"
	"github.com/pkg/errors"
	"io/ioutil"
	"net/http"
	"time"
	"xj.com/oos-data-service/error_handler"
	"xj.com/oos-data-service/service/object"
)

const (
	timeFormat       = "2006-01-02 15:04:05"
	objectIdHeader   = "X-Object-Id"
	createTimeHeader = "X-Create-Time"
)

type ObjectController struct {
	objectService *object.ObjectService
}

func New() (s *ObjectController) {
	s = new(ObjectController)
	s.objectService = object.New()
	return s
}

func (s *ObjectController) Get(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
	objectId := s.getObjectId(request)
	objectContent := s.objectService.Get(objectId)
	_, _ = writer.Write(objectContent)
}

func (s *ObjectController) Put(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	objectId := s.getObjectId(r)
	all, err := ioutil.ReadAll(r.Body)
	error_handler.HttpPanicIfError(errors.WithStack(err))

	if len(all) == 0 {
		error_handler.HttpPanicIfError(errors.New("对像的Payload不能为空。"))
	}

	createTimeStr := s.getCreateTime(r)
	timeOfObject, err := s.parseTimeFromStr(createTimeStr)
	error_handler.HttpPanicIfError(errors.WithStack(err))

	err = s.objectService.Upload(objectId, timeOfObject, all)
	error_handler.HttpPanicIfError(errors.WithStack(err))

	w.WriteHeader(http.StatusCreated)
}

func (s *ObjectController) getCreateTime(r *http.Request) string {
	createTimeStr := r.Header.Get(createTimeHeader)
	if len(createTimeStr) == 0 {
		error_handler.HttpPanicIfError(errors.New(createTimeHeader + "(格式：yyyy-MM-dd HH:mm:ss)不能为空。"))
	}

	return createTimeStr
}

func (s *ObjectController) getObjectId(r *http.Request) string {
	objectId := r.Header.Get(objectIdHeader)
	if len(objectId) == 0 {
		error_handler.HttpPanicIfError(errors.New(objectIdHeader + "不能为空。"))
	}

	return objectId
}

func (*ObjectController) parseTimeFromStr(tiStr string) (time.Time, error) {
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeFormat, tiStr, loc)
	if err != nil {
		return time.Now(), err
	}
	return theTime, nil
}
